/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.dto.CourseandteachDto;
import me.zhengjie.modules.system.domain.vo.CourseandteachVo;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.TeachService;
import me.zhengjie.modules.system.domain.vo.TeachQueryCriteria;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-04-21
**/
@Service
@RequiredArgsConstructor
public class TeachServiceImpl extends ServiceImpl<TeachMapper, Teach> implements TeachService {

    private final TeachMapper teachMapper;

    private final UserMapper userMapper;

    private final TeachandteacherMapper teachandteacherMapper;

    private final CourseandteachMapper courseacherMapper;

    private final  SchoolteachMapper schoolteachMapper;

    private final TeachauditMapper teachauditMapper;

    public CourseandteachVo queryCourseTeach(Integer courseId){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();

        User currentUser = userMapper.findByUsername(currentUserName);

//        List<Long> schoolteachIds = new ArrayList<>();
//        List<Schoolteach> teachList = schoolteachMapper.findSchoolteach(Math.toIntExact(currentUser.getDeptId()));
//
//        for(Schoolteach schoolteach:teachList){
//            schoolteachIds.add(Long.valueOf(schoolteach.getTeachId()));
//        }
//
//        //查询课程已经绑定的教材
//        List<Courseandteach> courseandteachList = courseacherMapper.queryCourseAndTeachMsg(courseId);
//
//        List<Long> teachIds = new ArrayList<>();
//        for(Courseandteach courseandteach:courseandteachList){
//            teachIds.add(Long.valueOf(courseandteach.getTeachid()));
//        }
//        CourseandteachVo courseandteachDto = new CourseandteachVo();
//        if(!teachIds.isEmpty()){
//            List<Teach> courseTeachList =  teachMapper.selectBatchIds(schoolteachIds);
//            courseandteachDto.setTeachList(courseTeachList);
//        }
//        if(!teachIds.isEmpty()){
//            List<Teach> courseTeachList =  teachMapper.selectBatchIds(teachIds);
//            courseandteachDto.setTeachList(courseTeachList);
//        }
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("courseId", courseId);
        List<Courseandteach> courseandteachList = courseacherMapper.selectList(queryWrapper);

        List<Long> teachIds = new ArrayList<>();
        for(Courseandteach courseandteach:courseandteachList){
            teachIds.add(Long.valueOf(courseandteach.getTeachid()));
        }

        CourseandteachVo courseandteachDto = new CourseandteachVo();
        if(!teachIds.isEmpty()){
            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("id",teachIds);
            courseandteachDto.setTeachList(teachMapper.selectList(queryWrapper1));
        }

//        if(!teachIds.isEmpty()){
//            courseandteachDto.setTeachIds(teachIds);
//        }

        return courseandteachDto;
    }
    public Long queryTeachCount(Integer schoolId){

        return teachMapper.findCountBySchoolId(schoolId);
    }


//    @Override
    public List<Teach> queryTeach(List<Long> ids){
        if(ids.size()!=0){

            return teachMapper.findMsgByIds(ids);
        } else {
            return null;
        }
    }

    @Override
    public PageResult<Teach> queryAll(TeachQueryCriteria criteria, Page<Object> page){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<Schoolteach>();
        queryWrapper.eq("schoolId", currentUser.getDeptId());
        List<Schoolteach> schoolteachList = schoolteachMapper.selectList(queryWrapper);

        List<Integer> schoolTeachIds = new ArrayList<>();
        for (Schoolteach schoolTeach :schoolteachList){
            schoolTeachIds.add(schoolTeach.getTeachId());
        }


        criteria.setTeachIds(schoolTeachIds);

        IPage<Teach> currentteachList = new Page<>();
        PageResult<Teach> teachList = PageUtil.toPage(currentteachList);
        if(schoolTeachIds !=null && schoolTeachIds.size()==0){
            return teachList;
        }
        List<Long> ids = new ArrayList<>();


        teachList = PageUtil.toPage(teachMapper.findManageAll(criteria, page));
        teachList.getContent().forEach(teach -> {
            if(teach.getUserid()!=null){
                ids.add(teach.getUserid());
            }
        });
        List<User> userList = new ArrayList<>();

        if(!ids.isEmpty()){
            userList = userMapper.selectBatchIds(ids);
        }


        List<User> finalUserList = userList;
        teachList.getContent().forEach(teachItem -> {
            finalUserList.forEach(user -> {
                if(teachItem.getUserid() == user.getId()){
                    teachItem.setUsername(user.getUsername());
                }
            });
        });
        return teachList;
    }
    @Override
    public PageResult<Teach> queryViewTeach(Integer courseId, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        //查询学校已绑定的教材
        QueryWrapper queryWrapper = new QueryWrapper<Schoolteach>();
        queryWrapper.eq("schoolId",currentUser.getDeptId());
        List<Schoolteach>   schoolteachList = schoolteachMapper.selectList(queryWrapper);
        //获取该学校所有教材id
        List<Integer> schoolTeachIds = new ArrayList<>();
        for(Schoolteach schoolteach :schoolteachList){
            schoolTeachIds.add(schoolteach.getTeachId());
        }


        //查询教师拥有教材
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userId",currentUser.getId());
        List<Teachandteacher>  teacherteachList = teachandteacherMapper.selectList(queryWrapper1);

        //获取教师拥有教材id
        List<Integer> teacherTeachIds = new ArrayList<>();
        for(Teachandteacher teacherteach :teacherteachList){
            teacherTeachIds.add(Math.toIntExact(teacherteach.getTeachid()));
        }
        //查询是否公开
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("isOpen",1);
        queryWrapper2.eq("state",1);
        queryWrapper2.in("id",schoolTeachIds);
        List<Teach>  teachList = new ArrayList<>();
        if(schoolTeachIds.size()!=0){
            teachList = teachMapper.selectList(queryWrapper2);
        }


        List<Long> publicteachIds = new ArrayList<>();
        for(Teach teach :teachList){
            publicteachIds.add(teach.getId());
        }

        //查询自身绑定的教材
        if(!teacherTeachIds.isEmpty()){
            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("state",1);
            queryWrapper3.in("id",teacherTeachIds);
            List<Teach>  userteachList = teachMapper.selectList(queryWrapper3);
            for(Teach teach :userteachList){
                if(!containsElement(publicteachIds,teach.getTeachTid())){
                    teachList.add(teach);
                }
            }

        }

        CourseandteachVo courseandteachVo = new CourseandteachVo();
        courseandteachVo.setTeachList(teachList);

        //查询课程已经绑定的教材
        List<Courseandteach> courseandteachList = courseacherMapper.queryCourseAndTeachMsg(courseId);

        List<Long> teachIds = new ArrayList<>();
        for(Courseandteach courseandteach:courseandteachList){
            teachIds.add(Long.valueOf(courseandteach.getTeachid()));
        }

        if(!teachIds.isEmpty()){
            courseandteachVo.setTeachIds(teachIds);
        }


//        return courseandteachVo;
        List<Long> ids = new ArrayList<>();
        for(Teach teach:courseandteachVo.getTeachList()){
            ids.add(teach.getId());
        }
        IPage<Teach> teachList1 = new Page<>();

        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.in("id",ids);
        Page page1 = new Page<>(page.getCurrent(),page.getSize());
        if(ids.size()!=0){
            teachList1 = teachMapper.selectPage(page1,queryWrapper5);
        }

        return PageUtil.toPage(teachList1);
    }

    public boolean containsElement(List<Long> array, Long target) {
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i) ==  target) {
                return true;
            }
        }
        return false;
    }
    @Override
    public PageResult<Teach> queryTeacherAll(TeachQueryCriteria criteria, Page<Object> page){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",currentUser.getId());
        List<Teachandteacher> teachandteacherList = teachandteacherMapper.selectList(queryWrapper);
        //获取需要编辑的教材
        List<Long> teachIds = new ArrayList<>();
        for(Teachandteacher teachandteacher:teachandteacherList){
            teachIds.add(teachandteacher.getTeachid());
        }
        //查询绑定id的教材
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id",teachIds);

        if(criteria.getName()!="" && criteria.getName()!=null){
            queryWrapper1.like("name",criteria.getName());
        }


        Page page1 = new Page<>(page.getCurrent(),page.getSize());
        Page<Teach> teachList = new Page<>();
        if(!teachIds.isEmpty()){

            teachList = teachMapper.selectPage(page1,queryWrapper1);
        }
//        PageResult<Teach> teachResultList = PageUtil.toPage(teachList);
//        teachList.getContent().forEach(teach -> {
//            if(teach.getUserid() == currentUser.getId()){
//                teach.setUsername(currentUser.getUsername());
//            }
//        });
        return PageUtil.toPage(teachList);
    }

    @Override
    public List<Teach> queryAll(TeachQueryCriteria criteria){
        return teachMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(Teach resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        resources.setUserid(currentUser.getId());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成时间戳
        String timestamp = sdf.format(new Date());
        resources.setCreatetime(timestamp);

        resources.setLastupdatetime(new Date().getTime());



        save(resources);
        for(Long item:resources.getTeacherIds()){
            Teachandteacher teachandteacher = new Teachandteacher();
            teachandteacher.setUserid(item);
            teachandteacher.setTeachid(resources.getId());
            teachandteacher.setSchoolid(currentUser.getDeptId());
//            teachandteacher.setAvatarName(resources.getAvatarName());
            teachandteacherMapper.insert(teachandteacher);
        }
        Schoolteach schoolteach = new Schoolteach();
        schoolteach.setSchoolId(Math.toIntExact(currentUser.getDeptId()));
        schoolteach.setTeachId(Math.toIntExact(resources.getId()));
        schoolteachMapper.insert(schoolteach);

        Teachaudit teachaudit = new Teachaudit();
        teachaudit.setTeachId(resources.getId());
        teachaudit.setCreateTime(resources.getCreatetime());
        teachaudit.setContent(resources.getRejectReason());
        teachaudit.setState(resources.getIsAudit());
        teachaudit.setUserId(currentUser.getId());
        teachauditMapper.insert(teachaudit);
        return resources.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Teach resources) {
        Teach teach = getById(resources.getId());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        teach.setUserid(currentUser.getId());
        teach.setLastupdatetime(new Date().getTime());
        teach.copy(resources);
        saveOrUpdate(teach);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成时间戳
        String timestamp = sdf.format(new Date());

        Teachaudit teachaudit = new Teachaudit();
        teachaudit.setTeachId(resources.getId());
        teachaudit.setCreateTime(timestamp);
        teachaudit.setContent(resources.getRejectReason());
        teachaudit.setState(resources.getIsAudit());
        teachaudit.setUserId(currentUser.getId());
        teachauditMapper.insert(teachaudit);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teachId",teach.getId());
        queryWrapper.eq("schoolId",currentUser.getDeptId());

        if(resources.getTeacherIds()!=null){
            teachandteacherMapper.delete(queryWrapper);
            for(Long item:resources.getTeacherIds()){
                Teachandteacher teachandteacher = new Teachandteacher();
                teachandteacher.setUserid(item);
                teachandteacher.setTeachid(resources.getId());
                teachandteacher.setSchoolid(currentUser.getDeptId());
                teachandteacherMapper.insert(teachandteacher);
            }
        }

    }

    public void updateTeachAudit(Teach resources) {
        Teach teach = getById(resources.getId());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        teach.setUserid(currentUser.getId());
        teach.setLastupdatetime(new Date().getTime());
        teach.copy(resources);
        saveOrUpdate(teach);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成时间戳
        String timestamp = sdf.format(new Date());


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Teach> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Teach teach : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", teach.getName());
            map.put("图标", teach.getIcon());
            map.put("内容", teach.getContent());
            map.put("状态", teach.getState());
            map.put("排序", teach.getOrderby());
            map.put("创作人", teach.getUserid());
            map.put("创建时间", teach.getCreatetime());
            map.put("操作时间", teach.getLastupdatetime());
            map.put("教材分类", teach.getTeachtypeid());
            map.put("作者", teach.getAuthor());
            map.put("出版社", teach.getPress());
            map.put("出版号", teach.getPressnum());
            map.put("教材协作者", teach.getTextbookcollaborator());
            map.put("教材描述", teach.getInfo());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


}